package cn.lzj.org.controller;

import cn.lzj.basic.util.AjaxResult;
import cn.lzj.basic.util.PageList;
import cn.lzj.org.domain.Department;
import cn.lzj.org.query.DepartmentQuery;
import cn.lzj.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/**
 *    这是RestFul风格的接口,目的是为了和前端接口对接
 *    部门管理接口
 *        要求前后端传递参数必须要使用json对象
 *     写接口的三要素
 *         1.请求地址----
 *         2.请求参数----
 *         3.返回值----
 *      接口注解有  ①@GetMapping =@RequestMapping(value="/id",method = RequestMethod.GET)
 *                ②@Postapping
 *                ③@PutMapping
 *                ④@PatchMapping
 */
@RestController//这个注解相当于@Controller+@RequestBody
@RequestMapping("/dept")  //路径:local host:8080/dept
public class DepartmentController {
    //注入service层的支持
    @Autowired
    private IDepartmentService departmentService;

    //新增和修改  请求类型为put
    @PutMapping  //路径: localhost:8080/dept/{id},id是占位符,可变
    public Object addOrUpdate(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                departmentService.add(department);
            } else {
                departmentService.update(department);
            }
            return AjaxResult.util();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.util()
                   .setsuccess(false)
                    .setmessage("噢哟，系统报错了，我们正在殴打程序员！！!");
        }
    }
    //删除   delete
    //@PathVariable映射 URL 绑定的占位符
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id")Long id){
        try {
            departmentService.remove(id);
            return AjaxResult.util();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.util()
                    .setsuccess(false)
                    .setmessage("噢哟，系统报错了，我们正在殴打程序员！！!");
        }
    }
    //获取单条数据的逻辑  请求类型:get
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id")Long id){
        return departmentService.queryById(id);
    }
    //获取所有数据的方法  请求类型:get
    @GetMapping
    public List<Department> queryAll(){
        return departmentService.queryAll();
    }
    //分页和高级查询  请求类型是post
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);
    }

}
